using System;
using System.Collections.Generic;
using System.IO;
//using System.Text;
using Petra.Gis.Geometry;
using Petra.Gis.Geometry.Support;
using Petra.Gis.DataServices.WKB.Support;

namespace Petra.Gis.DataServices.WKB
{
  public partial class GeometryFactory
  {

    /***********************************************
    * 28.8.2007
    * 
    * creates Polygon
    * from intergraph blob structure
    * 
    * asida@centrum.cz, initial implementation
    *************************************************/
    private static GeometryBase binaryToPolygon(BinaryReader mBReader/*, int arrayOffset*/, System.Type parentGeomType)
    {
      int numRings;

      //read data endian first
      //mBReader.BaseStream.Position = arrayOffset;
      WKB.ByteOrder dataEndian = (WKB.ByteOrder)mBReader.ReadByte();

      Polygon oGeom = new Polygon();

      //skip geometry type
      //mBReader.BaseStream.Position = arrayOffset + 5;
      mBReader.BaseStream.Position += 4;
      numRings = EndianConverter.ToInt32(mBReader.ReadInt32(), dataEndian);

      ////oldschool way replaced
      //fixed (byte* bPtr = &vData[arrayOffset + 5])
      //{
      //  //get num of rings
      //  int* _numRings = (Int32*)(bPtr);
      //  numRings = EndianConverter.ToInt32(*_numRings, dataEndian);
      //}

      //process rings
      //int pos = 9; //begin pos of first ring
      for (int i = 0; i < numRings; i++)
      {
        LineRing tmpGeom = (LineRing)binaryToLineRing(mBReader/*, arrayOffset + pos*/, typeof(Polygon), dataEndian);
        oGeom.Add(tmpGeom);
        //int binarySize = 4 + (tmpGeom.coordList.Count * (int)tmpGeom.coordList.dimension); //4 = numpoints
        //pos = pos + binarySize;
      }
      
      return oGeom;
    }




    /***********************************************
    * 28.8.2007
    * 
    * creates intergraph blob structure 
    * from Polygon
    * 
    * asida@centrum.cz, initial implementation
    *************************************************/
    private static byte[] polygonToBinary(GeometryBase geometry)
    {
      //cast to Polygon first
      Polygon _polygon = (Polygon)geometry;

      System.IO.MemoryStream oIMStream = new System.IO.MemoryStream();
      System.IO.BinaryWriter mBWriter = new System.IO.BinaryWriter(oIMStream);

      //oIMStream.Position = 0;

      mBWriter.Write((byte)EndianConverter.GetCurrentPlatformEndian());
      mBWriter.Write((Int32)WKB.WKBGeometryTypes.Polygon);

      byte[] tmp = collectionItemsToBinary(_polygon, 0);
      mBWriter.Write(tmp);

      return oIMStream.ToArray();
    }
  }
}
